const exp_email = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
const exp_phone = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
import { _ruleConfig } from '../../../../../config.js';
export class Rule {
	constructor(area, config = {}) {
		this.rules = [];
		this.area = area;
		this.config = config;
		this.ruleData = this.getRuleData();
	}
	buildByFn(fn, label) {
		return {
			trigger: ['blur', 'submit'],
			validator: async (rule, value, callback) => {
				const msg = await fn(value, label);
				return this.area.hook.hookBuildRule(msg, callback);
			},
		};
	}
	getRuleData() {
		const { config } = this;
		// ====================自定义规则====================
		const injectRules = {};
		const { ruleData } = _ruleConfig;
		if (ruleData) {
			for (let name in ruleData) {
				const v = ruleData[name];
				injectRules[name] = label => {
					return typeof v === 'function' ? this.buildByFn(v, label) : v;
				}
			}
		}
		// ====================自定义规则====================
		return {
			required(label) {
				return { required: true, message: `${label} 必填`, ...config };
			},
			range(label, min, max) {
				return {
					min,
					max,
					message: `${label} 长度控制在${min}到${max}`,
					...config,
				};
			},
			// 校验数组必须有内容
			requireArr: label => {
				return this.buildByFn((value) => {
					if (Array.isArray(value) && value?.length) {
						// 校验通过，放行
					} else {
						return `${label} 需要非空数组`
					}
				}, label)
			},
			email: label => {
				return this.buildByFn((value) => {
					if (exp_email.test(value)) {
						// 校验通过，放行
					} else {
						return `${label} 邮箱格式有误`
					}
				}, label)
			},
			phone: label => {
				return this.buildByFn((value) => {
					if (exp_phone.test(value)) {
						// 校验通过，放行
					} else {
						return `${label} 手机格式有误`
					}
				}, label)
			},
			...injectRules,
		};
	}
	init(rules, label = '') {
		if (Array.isArray(rules)) {
			return rules.map((rule) => {
				if (typeof rule === 'string') {
					return this.ruleData[rule](label);
				} else if (Array.isArray(rule)) {
					return this.ruleData.range(label, ...rule);
				} else if (typeof rule === 'function') {
					return this.buildByFn(rule, label)
				}
				return rule;
			});
		}
	}
}